<template>
  <div class="employees-detail-container">
    <div class="app-container">
      <el-card>
        <!-- 放置表单 -->
        <!-- el-form: :model :rules -->
        <!-- el-form-item prop -->
        <!-- el-input v-model -->
        <el-form
          ref="userForm"
          label-width="120px"
          style="margin-left: 120px; margin-top: 30px"
          :model="userInfo"
          :rules="rules"
        >
          <el-form-item label="姓名:" prop="username">
            <el-input v-model="userInfo.username" style="width: 300px" />
          </el-form-item>
          <el-form-item label="手机">
            <el-input v-model="userInfo.mobile" style="width: 300px" disabled />
          </el-form-item>
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker
              v-model="userInfo.timeOfEntry"
              type="date"
              class="inputW"
            />
          </el-form-item>
          <el-form-item label="员工头像">
            <ImageUpload ref="staffPhoto" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editEmployee">更新</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getUserAvatarApi } from '@/api/user'
import { editEmployeeApi } from '@/api/employees'
export default {
  name: 'EmployeesDetail',
  data() {
    return {
      userInfo: {},
      rules: {
        username: [
          { required: true, message: '姓名不可为空', trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '入职时间不可为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  created() {
    this.getUserAvatar()
  },
  methods: {
    /**
     * 编辑员工
     */
    editEmployee() {
      this.$refs.userForm.validate(async flag => {
        if (!flag) return
        // 先获取头像，获取头像 赋值给userInfo
        const staffPhoto = this.$refs.staffPhoto
        // 处理上传中的逻辑
        if (!staffPhoto.isAllUploadSuccess) {
          this.$message.warning('还有图片正在上传中，请上传完后在更新')
          return
        }
        // 头像不可为空
        if (staffPhoto.fileList[0]?.url) {
          this.userInfo.staffPhoto = staffPhoto.fileList[0].url
        } else {
          this.$message.warning('头像不可为空')
          return
        }
        await editEmployeeApi(this.userInfo)
        this.$message.success('恭喜！修改成功')
      })
    },
    /**
     * 获取用户信息
     */
    async getUserAvatar() {
      const res = await getUserAvatarApi(this.id)
      this.userInfo = res.data
      // 进行头像的回显
      this.$refs.staffPhoto.fileList = [
        { url: res.data.staffPhoto }
      ]
    }
  }
}
</script>
